const fs = require("fs");
const COS = require("cos-nodejs-sdk-v5");
const request = require("request");
const cosConfig = {
    Bucket: "7072-prod-6g4e5x5l5eb5bac2-1324401249", // 填写云托管对象存储桶名称
    Region: "ap-shanghai", // 存储桶地域，默认是上海，其他地域环境对应填写
};
const downloadUrl = `https://${cosConfig.Bucket}.tcb.qcloud.la`;
initcos();

/**
 * 封装的上传文件函数
 * @param {*} cloudpath 上传的云上路径
 * @param {*} filepath 本地文件路径
 */
async function uploadFile(cloudpath, filepath) {
    const authres = await call({
        url: "http://api.weixin.qq.com/_/cos/metaid/encode",
        method: "POST",
        data: {
            openid: "", // 填写用户openid，管理端为空字符串
            bucket: cosConfig.Bucket,
            paths: [cloudpath],
        },
    });
    try {
        // console.log("authres",authres);
        const auth = JSON.parse(authres);
        const res = await this.cos.putObject({
            Bucket: cosConfig.Bucket,
            Region: cosConfig.Region,
            Key: cloudpath,
            StorageClass: "STANDARD",
            Body: fs.createReadStream(filepath),
            ContentLength: fs.statSync(filepath).size,
            Headers: {
                "x-cos-meta-fileid": auth.respdata.x_cos_meta_field_strs[0],
            },
        });
        if (res.statusCode === 200) {
            return {
                status: 1,
                url: downloadUrl + cloudpath,
            };
        } else {
            return {
                status: 0,
            };
        }
    } catch (e) {
        console.log("weixin_result_error",e);
        return {
            status: 0,
        };
    }
}
async function listFiles(path){
    try{
        const res = await this.cos.getBucket({
            Bucket: cosConfig.Bucket,
            Region: cosConfig.Region,
            Prefix: path,
            Delimiter: '/'
        });
        return {status:1,data:res.Contents};
    }catch(e){
        return {status:0};
    }
}
async function hasExist(key){
    try{
        const res = await this.cos.headObject({
            Bucket: cosConfig.Bucket,
            Region: cosConfig.Region,
            Key: key
        });
        // console.log("getFile:",res);
        if(res){
            return {status:1};
        }else{
            return {status:0};
        }
        
    }catch(e){
        return {status:0};
    }
}
// async function getFile(key){
//     try{
//         const res = await this.cos.getObjectUrl({
//             Bucket: cosConfig.Bucket,
//             Region: cosConfig.Region,
//             Key: key,
//             Sign: false
//         });
//         console.log("getFile:",res + ",end");
//         return {status:1,url:res};
//     }catch(e){
//         return {status:0};
//     }
// }
async function deleteFile(path) {
    try{
        await this.cos.deleteObject(
            {
                Bucket: cosConfig.Bucket /* 填入您自己的存储桶，必须字段 */,
                Region: cosConfig.Region /* 存储桶所在地域，例如ap-beijing，必须字段 */,
                Key: path /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
            }
            // function (err, data) {
            //     if(err) reject(err)
            //     resolve(data);
            // }
        );
        return {status:1};
    }catch(e){
        return {status:0};
    }
    
}
function call(obj) {
    return new Promise((resolve, reject) => {
        request(
            {
                url: obj.url,
                method: obj.method || "POST",
                headers: {
                    "content-type": "application/json",
                },
                body: JSON.stringify(obj.data || {}),
            },
            function (err, response) {
                // console.log("err:",err,response);
                if (err) {
                    reject(err);
                }else{
                    resolve( response.body);
                }
            }
        );
    });
}

async function initcos() {
    try {
        this.cos = new COS({
            getAuthorization: async function (options, callback) {
                try{
                    const res = await call({
                        url: "http://api.weixin.qq.com/_/cos/getauth",
                        method: "GET",
                    });
                    const info = JSON.parse(res);
                    const auth = {
                        TmpSecretId: info.TmpSecretId,
                        TmpSecretKey: info.TmpSecretKey,
                        SecurityToken: info.Token,
                        ExpiredTime: info.ExpiredTime,
                    };
                    callback(auth);
                }catch(e){
                    console.log("COS初始化失败", );
                }
               
            },
        });
        console.log("COS初始化成功");
    } catch (e) {
        console.log("COS初始化失败", );
    }
}

module.exports = {
    uploadFile,deleteFile,listFiles
};
